package com.yanyu.space.common.core;

import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.yanyu.space.common.core.bootlog.BootstrapLog;
import com.yanyu.space.common.core.exception.GlobalExceptionHandler;
import com.yanyu.space.common.core.util.AppContext;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;

@Configuration
@EnableAspectJAutoProxy(exposeProxy = true)
@Import(value = {AppContext.class, BootstrapLog.class})
public class CoreAutoConfig {

    /**
     * 修改JacksonAutoConfiguration中ObjectMapper配置，解决long类型传到前台失真
     *
     * @return
     */
    @Bean
    @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
    public Jackson2ObjectMapperBuilderCustomizer longJackson2ObjectMapperBuilderCustomizer() {
        return jacksonObjectMapperBuilder -> {
            jacksonObjectMapperBuilder.serializers(new ToStringSerializer(Long.class));
            jacksonObjectMapperBuilder.serializers(new ToStringSerializer(Long.TYPE));
        };
    }

    /**
     * 异常统一处理类
     *
     * @return
     */
    @Bean
    @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
    public GlobalExceptionHandler globalExceptionHandler() {
        return new GlobalExceptionHandler();
    }

    @Bean
    public AppContext appContext() {
        return new AppContext();
    }

}
